<template>
  <div class="company-page page-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="list">
        <div class="home-icon">
          <i class="iconfont icon-home"></i>
        </div>
        <div class="item">
          <router-link to="/">
            <span class="text">首页</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <span class="text">公司管理</span>
        </div>
      </div>
      <h1 class="page-title">公司管理</h1>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <button class="v-button primary" @click="openAddModal">
        <i class="iconfont icon-add"></i> 添加公司
      </button>

      <!-- 搜索框 -->
      <div class="search-wrapper">
        <div class="search-input">
          <i class="iconfont icon-search"></i>
          <input
            v-model="searchQuery"
            placeholder="搜索公司名称/地址/联系电话"
            @keyup.enter="handleSearch"
          />
          <i
            v-if="searchQuery"
            class="iconfont icon-close"
            @click="handleSearchClear"
          ></i>
        </div>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-bar">
      <div class="filter-group">
        <label>公司状态:</label>
        <BaseSelect
          v-model="statusFilter"
          :options="[...statusOptions, { value: '', text: '全部' }]"
          placeholder="请选择状态"
          @change="handleFilter"
        />
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>公司名称</th>
            <th>地址</th>
            <th>联系电话</th>
            <th>创建时间</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="company in companyList" :key="company.id">
            <td>{{ company.id }}</td>
            <td>{{ company.name }}</td>
            <td>{{ company.address || '-' }}</td>
            <td>{{ company.contact_phone || '-' }}</td>
            <td>{{ formatDate(company.created_at * 1000) }}</td>
            <td>
              <span class="status-badge" :class="company.status === '1' ? 'active' : 'inactive'">
                {{ company.status === '1' ? '正常' : '禁用' }}
              </span>
            </td>
            <td class="control">
              <button class="v-button" @click="openEditModal(company)">
                <i class="iconfont icon-edit"></i> 编辑
              </button>
              <button class="v-button danger" @click="confirmDelete(company)">
                <i class="iconfont icon-delete"></i> 删除
              </button>
              <button class="v-button" @click="confirmToggleStatus(company)">
                <i class="iconfont icon-switch"></i> {{ company.status === '1' ? '禁用' : '启用' }}
              </button>
            </td>
          </tr>
          <tr v-if="loading">
            <td colspan="7" class="loading">加载中...</td>
          </tr>
          <tr v-else-if="companyList.length === 0">
            <td colspan="7" class="empty-row">
              <i class="iconfont icon-empty"></i>
              <p>暂无数据</p>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="totalPages > 0 && !loading">
      <div class="page-info">
        共 {{ totalCount }} 条记录，第 {{ currentPage }} / {{ totalPages }} 页
      </div>
      <div class="v-pagination">
        <button
          class="v-button"
          :disabled="currentPage === 1"
          @click="handlePageChange(1)"
        >
          首页
        </button>
        <button
          class="v-button"
          :disabled="currentPage === 1"
          @click="handlePageChange(currentPage - 1)"
        >
          上一页
        </button>
        <button
          v-for="page in visiblePages"
          :key="page"
          class="v-button"
          :class="{ active: currentPage === page }"
          @click="handlePageChange(page)"
        >
          {{ page }}
        </button>
        <button
          class="v-button"
          :disabled="currentPage === totalPages"
          @click="handlePageChange(currentPage + 1)"
        >
          下一页
        </button>
        <button
          class="v-button"
          :disabled="currentPage === totalPages"
          @click="handlePageChange(totalPages)"
        >
          末页
        </button>
      </div>
    </div>

    <!-- 公司编辑弹窗 - 使用vPopup组件 -->
    <vPopup
      v-model="showModal"
      :title="isEdit ? '编辑公司' : '添加公司'"
      :confirmText="isEdit ? '保存' : '添加'"
      width="500px"
      @confirm="handleSubmit"
    >
      <form class="vForm" @submit.prevent="handleSubmit">
        <div class="form-group">
          <label class="form-label" for="company-name">公司名称 <span class="required">*</span></label>
          <input
            class="form-input"
            id="company-name"
            v-model="formData.name"
            type="text"
            placeholder="请输入公司名称"
            required
          />
        </div>
        <div class="form-group">
          <label class="form-label" for="company-address">公司地址</label>
          <input
            class="form-input"
            id="company-address"
            v-model="formData.address"
            type="text"
            placeholder="请输入公司地址"
          />
        </div>
        <div class="form-group">
          <label class="form-label" for="company-phone">联系电话</label>
          <input
            class="form-input"
            id="company-phone"
            v-model="formData.contact_phone"
            type="text"
            placeholder="请输入联系电话"
          />
        </div>
        <div class="form-group">
          <label class="form-label" for="company-status">状态</label>
            <div class="toggle-wrapper">
              <vToggle v-model="formData.status" />
              <span class="toggle-label">{{ formData.status ? '启用' : '禁用' }}</span>
            </div>
        </div>
      </form>
    </vPopup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { get, post } from "@/utils/request";
import { formatDate } from "@/utils/date";
import { vConfirm } from "@/plugins/vConfirm";
import { vToast } from "@/plugins/vToast";
import BaseSelect from '@/components/BaseSelect.vue';

// 数据
const companyList = ref([]);
const loading = ref(false);
const searchQuery = ref("");
const statusFilter = ref("");

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
const totalPages = ref(0);
const maxVisible = ref(5);

// 下拉选项
const statusOptions = [
  { value: 1, text: '启用' },
  { value: 0, text: '禁用' }
];

// 弹窗相关
const showModal = ref(false);
const isEdit = ref(false);
const formData = ref({
  id: '',
  name: '',
  address: '',
  contact_phone: '',
  status: 1
});



// 计算可见页码
const visiblePages = computed(() => {
  const pages = [];
  const half = Math.floor(maxVisible.value / 2);
  let start = currentPage.value - half;
  let end = currentPage.value + half;

  if (start < 1) {
    start = 1;
    end = Math.min(maxVisible.value, totalPages.value);
  }

  if (end > totalPages.value) {
    end = totalPages.value;
    start = Math.max(1, end - maxVisible.value + 1);
  }

  for (let i = start; i <= end; i++) {
    pages.push(i);
  }

  return pages;
});

// 获取公司列表
const fetchCompanies = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
    };

    if (searchQuery.value) {
      params.keyword = searchQuery.value;
    }

    if (statusFilter.value !== "") {
      params.status = statusFilter.value;
    }

    const res = await get("/company/list", params);

    if (res.code === 200) {
      companyList.value = res.data.list;
      totalCount.value = res.data.pagination.total;
      totalPages.value = Math.ceil(totalCount.value / pageSize.value);
    }
  } catch (error) {
    vToast.error("获取公司列表失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchCompanies();
};

// 清空搜索
const handleSearchClear = () => {
  searchQuery.value = "";
  currentPage.value = 1;
  fetchCompanies();
};

// 筛选
const handleFilter = () => {
  currentPage.value = 1;
  fetchCompanies();
};

// 分页
const handlePageChange = (page) => {
  if (page < 1 || page > totalPages.value || page === currentPage.value) {
    return;
  }
  currentPage.value = page;
  fetchCompanies();
};

// 打开添加弹窗
const openAddModal = () => {
  isEdit.value = false;
  formData.value = {
    id: '',
    name: '',
    address: '',
    contact_phone: '',
    status: '1'
  };
  showModal.value = true;
};

// 打开编辑弹窗
const openEditModal = async (company) => {
  isEdit.value = true;
  formData.value = {
    id: company.id,
    name: company.name,
    address: company.address || '',
    contact_phone: company.contact_phone || '',
    status: company.status
  };
  showModal.value = true;
};

// 关闭弹窗
const closeModal = () => {
  showModal.value = false;
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 确保status是数字类型（1或0）而不是布尔值
    const submitData = {
      ...formData.value,
      status: formData.value.status ? 1 : 0
    };
    
    let res;
    if (isEdit.value) {
      res = await post("/company/update", submitData);
    } else {
      res = await post("/company/create", submitData);
    }

    if (res.code === 200) {
      vToast.success(isEdit.value ? "公司更新成功" : "公司创建成功");
      closeModal();
      fetchCompanies();
    } else {
      vToast.error(res.msg || (isEdit.value ? "更新失败" : "创建失败"));
    }
  } catch (error) {
    vToast.error(isEdit.value ? "更新失败" : "创建失败");
    console.error(error);
  }
};

// 删除确认
const confirmDelete = (company) => {
  vConfirm({
    message: `确定要删除公司【${company.name}】吗？`,
    onConfirm: () => deleteCompany(company.id)
  });
};

// 删除公司
const deleteCompany = async (id) => {
  try {
    const res = await post("/company/delete", { id });

    if (res.code === 200) {
      vToast.success("公司删除成功");
      fetchCompanies();
    } else {
      vToast.error(res.msg || "删除失败");
    }
  } catch (error) {
    vToast.error("删除失败");
    console.error(error);
  }
};

// 切换公司状态确认
const confirmToggleStatus = (company) => {
  const action = company.status === '1' ? '禁用' : '启用';
  vConfirm({
    message: `确定要${action}公司【${company.name}】吗？`,
    onConfirm: () => toggleStatus(company)
  });
};

// 切换公司状态
const toggleStatus = async (company) => {
  try {
    const res = await post("/company/update", {
      id: company.id,
      status: company.status === '1' ? '0' : '1',
    });

    if (res.code === 200) {
      vToast.success(`公司${company.status === '1' ? '禁用' : '启用'}成功`);
      fetchCompanies();
    } else {
      vToast.error(res.msg || "操作失败");
    }
  } catch (error) {
    vToast.error("操作失败");
    console.error(error);
  }
};

// 初始化加载数据
onMounted(() => {
  fetchCompanies();
});
</script>

<style scoped lang="less">
.company-page {
  .breadcrumb {
    margin-bottom: 20px;
    
    .list {
      display: flex;
      align-items: center;
      font-size: 14px;
      
      .home-icon {
        color: #999;
      }
      
      .item {
        margin-right: 8px;
        
        .text {
          color: #333;
          
          &:hover {
            color: var(--v-theme);
          }
        }
      }
      
      .seperate {
        margin-right: 8px;
        color: #999;
      }
    }
    
    .page-title {
      margin-top: 10px;
      font-size: 24px;
      font-weight: 500;
      color: #333;
    }
  }

  .action-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 15px;

    .search-wrapper {
      flex: 1;
      max-width: 300px;
      margin-left: auto;

      .search-input {
        position: relative;
        display: flex;
        align-items: center;
        background: var(--v-card-bg);
        border-radius: var(--v-card-radius);
        border: 1px solid var(--v-border-color);
        padding: 0 10px;
        height: 36px;

        i {
          color: var(--v-text-light);
          margin-right: 8px;
        }

        input {
          flex: 1;
          border: none;
          background: transparent;
          outline: none;
          color: var(--v-text);

          &::placeholder {
            color: var(--v-text-light);
          }
        }

        .icon-close {
          cursor: pointer;
          margin-left: 8px;

          &:hover {
            color: var(--v-danger);
          }
        }
      }
    }
  }

  .filter-bar {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 20px;
    flex-wrap: wrap;

    .filter-group {
      display: flex;
      align-items: center;
      gap: 8px;

      label {
        font-size: 14px;
        color: var(--v-text);
      }

      select {
        padding: 6px 12px;
        border: 1px solid var(--v-border-color);
        border-radius: var(--v-card-radius);
        background: var(--v-card-bg);
        color: var(--v-text);
        outline: none;
        cursor: pointer;

        &:focus {
          border-color: var(--v-theme);
        }
      }
    }
  }

  .data-table {
    background: var(--v-card-bg);
    border-radius: var(--v-card-radius);
    overflow: hidden;
    margin-bottom: 20px;

    table {
      width: 100%;
      border-collapse: collapse;

      thead {
        background: var(--v-table-header-bg);

        th {
          padding: 12px 16px;
          text-align: left;
          font-weight: 500;
          color: var(--v-text);
          border-bottom: 1px solid var(--v-border-color);
        }
      }

      tbody {
        tr {
          border-bottom: 1px solid var(--v-border-color);

          &:last-child {
            border-bottom: none;
          }

          td {
            padding: 12px 16px;
            color: var(--v-text);
          }
        }
      }

      .loading,
      .empty-row {
        text-align: center;
        padding: 40px;
        color: var(--v-text-light);
      }

      .empty-row {
        .iconfont {
          font-size: 48px;
          margin-bottom: 10px;
          display: block;
        }
      }

      .status-badge {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: 500;

        &.active {
          background-color: rgba(40, 199, 111, 0.1);
          color: var(--v-success);
        }

        &.inactive {
          background-color: rgba(234, 84, 85, 0.1);
          color: var(--v-danger);
        }
      }

      .control {
        display: flex;
        align-items: center;
        gap: 8px;

        .v-button {
          padding: 4px 10px;
          font-size: 12px;
          min-width: auto;
          height: 28px;
          font-weight: 500;
          border-radius: 4px;
          border: 1px solid var(--v-border-color);
          background: var(--v-card-bg);
          color: var(--v-text);
          transition: all 0.3s ease;

          i {
            margin-right: 4px;
          }

          &:hover {
            border-color: var(--v-theme);
            color: var(--v-theme);
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          }

          &.danger {
            border-color: var(--v-danger);
            color: var(--v-danger);
          }

          &.danger:hover {
            background: rgba(234, 84, 85, 0.05);
            border-color: var(--v-danger);
          }

          &.success {
            border-color: var(--v-success);
            color: var(--v-success);
          }

          &.success:hover {
            background: rgba(40, 199, 111, 0.05);
            border-color: var(--v-success);
          }

          &:active {
            transform: translateY(0);
          }
        }
      }
    }
  }

  .toggle-wrapper {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .toggle-label {
    font-size: 14px;
    color: var(--v-text);
  }
  
  .pagination-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;

    .page-info {
      color: var(--v-text-light);
      font-size: 14px;
    }

    .v-pagination {
      display: flex;
      gap: 8px;

      .v-button {
        min-width: 36px;
        height: 36px;
        padding: 0 12px;

        &[disabled] {
          opacity: 0.5;
          cursor: not-allowed;
        }

        &.active {
          background: var(--v-theme);
          color: white;
        }
      }
    }
  }
  
  /* vPopup组件已包含弹窗样式，此处无需额外定义 */
  /* 表单样式已移至全局样式文件 src/assets/styles/main.less 中的 .vForm 类 */
}
</style>